<template>
  <div class="ccui-app-container">
    <div class="ccui-advanced-search-wrapper ccui-clearfix">
      <el-search
        ref="search"
        :formProp="formData"
        @search="search"
        :isShowSearch="isShowSearch"
        class="ccui-highsearch"
        :selectClear="true"
      >
        <div class="ccui-tab-wrapper">
          <el-button type="table-top-active" size="mini"
            >全部({{ totalNum }})</el-button
          >
        </div>
        <div class="ccui-extend-btn">
          <el-button
            size="mini"
            type="primary"
            @click="handleGoNew"
            icon="icon-ccui-add-sup"
            >新增仓库</el-button
          >
        </div>
        <template slot="search">
          <el-input
            v-model="formData.warehouseName"
            clearable
            searchLabel="仓库名称"
            placeholder="请输入仓库名称模糊查询"
          ></el-input>
          <el-input
            v-model="formData.warehouseCode"
            clearable
            searchLabel="仓库编号"
            placeholder="请输入仓库编号模糊查询"
          ></el-input>
          <el-input
            v-model="formData.warehousePlace"
            clearable
            searchLabel="库存地点"
            placeholder="请输入库存地点模糊查询"
          ></el-input>
        </template>
        <!-- 表单高级搜索 -->
        <el-input
          v-model="formData.warehouseName"
          clearable
          searchLabel="仓库名称"
          placeholder="请输入仓库名称模糊查询"
          slot="searchItem2"
        ></el-input>
        <el-input
          v-model="formData.warehouseCode"
          clearable
          searchLabel="仓库编号"
          placeholder="请输入仓库编号模糊查询"
          slot="searchItem1"
        ></el-input>
        <el-input
          v-model="formData.warehousePlace"
          clearable
          searchLabel="库存地点"
          placeholder="请输入库存地点模糊查询"
          slot="searchItem3"
        ></el-input>
      </el-search>
    </div>
    <div class="ccui-multifunctional-table-wrapper">
      <el-table
        v-if="tableHack"
        ref="multipleTable"
        :data="tableData"
        :fit="true"
        :row-style="rowClass"
        :cell-style="cellStyle"
        @cell-click="cellClick"
        border
        class="ccui-multifunctional-table"
        @selection-change="handleSelectionChange"
        @header-dragend="tableTitleWidth"
        :min-height="clientHeight"
      >
        <template v-for="(table, index) in tableTheadOptions">
          <el-table-column
            v-if="table.checked"
            :fixed="table.fixed || false"
            :type="table.type"
            :key="index"
            :label="table.label"
            :min-width="table.width"
            :prop="table.prop"
            :filters="table.filters"
            :align="table.align"
            :header-align="table.headerAlign || 'left'"
            :show-overflow-tooltip="true"
          ></el-table-column>
        </template>
        <el-table-column label="操作" width="90" fixed="right">
          <template slot-scope="scope">
            <el-button
              v-if="true"
              size="mini"
              type="text"
              @click="handleEditor(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="true"
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="ccui-table-footer" v-if="totalNum > 0">
        <div id="ccui-paging">
          <el-pagination
            :total="totalNum"
            :page-size="getLocalPageSize()"
            :current-page="formData.pageNo"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            background
            layout="total, sizes, prev, pager, next, jumper"
            popper-class="ccui-paging-page-size-popper"
            @prev-click="handlePrev"
            @next-click="handleNext"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-button
            class="ccui-pagination-btn"
            size="mini"
            type="default"
            @click="handleChangeSize('none')"
            >确定</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getStoreList, getStoreDelete } from "../api";
import { setSessionItem, getSessionItem, ishasAgentId } from "@/basa/utils";
import { getDetail } from "@/basa/api";
export default {
  name: "storeManagementList",
  data() {
    return {
      // 表格数据
      tableData: [],
      tableHack: true,
      // 表格命名
      tableName: this.tableList.storeManagementList,
      // 表格数据
      tableThead: [],
      // 锁定表格
      fixedTableThead: [
        {
          label: "序号",
          prop: "id",
          width: "38",
          checked: true,
          fixed: true,
          type: "index"
        },
        {
          label: "仓库编号",
          prop: "warehouseCode",
          width: "150",
          checked: true,
          fixed: true
        }
      ],
      // 非锁定表格
      unfixedTableThead: [
        {
          label: "仓库名称",
          prop: "warehouseName",
          width: "300",
          checked: true,
          align: "left"
        },
        {
          label: "库存地点",
          prop: "warehousePlace",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "填报单位",
          prop: "reportInOrgName",
          width: "200",
          checked: true,
          align: "left"
        },
        {
          label: "编制人",
          prop: "compilePeople",
          width: "60",
          checked: true,
          align: "left"
        },
        {
          label: "联系电话",
          prop: "warehousePhone",
          width: "130",
          checked: true,
          align: "left"
        },
        {
          label: "仓库描述",
          prop: "warehouseDescribe",
          width: "130",
          checked: true,
          align: "left"
        },
        {
          label: "编制时间",
          prop: "compileDate",
          width: "100",
          checked: true,
          align: "left"
        }
      ],
      clientHeight: 0, //内容高度
      //全部数量
      totalNum: 0,
      // 动态表格
      tableTheadOptions: [],
      // 弹框表格
      popoverShow: false,
      selectRow: [],
      selectData: [],
      // 高级搜索数据 start
      // 高级搜索提交数据
      isShowSearch: true,
      formData: {
        warehouseCode: "",
        warehouseName: "",
        warehousePlace: "",
        reportInOrgId: "",
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      },
      formDataSearch: {
        warehouseCode: "",
        warehouseName: "",
        warehousePlace: "",
        reportInOrgId: "",
        pageNo: 1,
        pageSize: this.getLocalPageSize(),
        isShowPageLoading: true
      },
      reportInOrgId: ""
      // 高级搜索数据 end
    };
  },
  activated() {
    this.$refs.search.resetForm();
    this.getDetail();
  },
  created() {
    this.clientHeight = document.documentElement.clientHeight - 294;
  },
  mounted() {
    //改变适口高度，高度改变
    window.onresize = () => {
      return (() => {
        this.clientHeight = document.documentElement.clientHeight - 294;
      })();
    };
    this.getDetail();
    this.initData();
  },
  methods: {
    initData() {
      this.setTableWidth();
      this.renderTable();
    },
    //填报单位
    getDetail() {
      getDetail({}).then(res => {
        if (res.data.code == 0) {
          this.reportInOrgId = res.data.data.orgId;
          this.formData.reportInOrgId = res.data.data.orgId;
          this.formDataSearch.reportInOrgId = res.data.data.orgId;
          this.getStoreList(this.formData); //请求列表
        }
      });
    },
    getStoreList(data) {
      getStoreList(data).then(res => {
        if (res.data.code == 0) {
          this.tableData = res.data.data.rows;
          this.formData.pageNo = res.data.data.pageNo;
          this.tableData.forEach(item => {
            if (item.compileDate) {
              item.compileDate = item.compileDate.split("00:00:00")[0];
            }
          });
          this.totalNum = res.data.data.recordsTotal;
        } else {
          this.$message({
            message: res.data.message,
            type: "success",
            showClose: true,
            ccuiCustom: true,
            duration: 2000
          });
        }
      });
    },
    // 新增
    handleGoNew(data) {
      this.$router.push({
        path: "/inventoryManagement/storeManagement/storeManagementAdd",
        query: { newAdd: 1 }
      });
    },
    //编辑
    handleEditor(row) {
      this.$router.push({
        path: "/inventoryManagement/storeManagement/storeManagementAdd",
        query: { id: row.id, isReference: row.isReference }
      });
    },
    //删除
    handleDelete(row) {
      this.$confirm("确定要删除吗?", "提示信息", {
        distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        customClass: "ccui-message-box-custom"
      })
        .then(() => {
          getStoreDelete({ id: row.id }).then(res => {
            if (res.data.code == 0) {
              this.getStoreList(this.formDataSearch);
            }
            this.$message({
              message: res.data.message,
              type: "success",
              showClose: true,
              ccuiCustom: true,
              duration: 2000
            });
          });
        })
        .catch(() => {});
    },
    // 查看
    cellClick(row, column, columnIndex) {
      if (column.label === "仓库编号") {
        this.$router.push({
          path: "/inventoryManagement/storeManagement/storeManagementDetails",
          query: { id: row.id }
        });
      }
    },
    // 根据返回状态显示不同的文字颜色
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "transparent" };
      }
      if (columnIndex == 1) {
        return { color: "#0089EF", cursor: "pointer" };
      }
    },
    // 默认渲染表格
    renderTable() {
      const localTableData = localStorage.getItem(this.tableName)
        ? JSON.parse(localStorage.getItem(this.tableName))
        : [];
      let unfixedTableThead = this.fixedTableThead.concat(
        this.unfixedTableThead
      );
      let localTableDataStr = localTableData.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );
      let unfixedTableTheadStr = unfixedTableThead.map(
        ({ label, prop, formatter, align }) =>
          JSON.stringify({ label, prop, formatter, align })
      );

      if (localTableData.length === unfixedTableThead.length) {
        let flag = localTableDataStr.every(item =>
          unfixedTableTheadStr.includes(item)
        );
        if (flag) {
          // 完全相同
          this.tableTheadOptions = localTableData;
          this.tableThead = localTableData;
          localTableData.forEach(item => {
            let index = this.unfixedTableThead.findIndex(
              cItem => item.prop === cItem.prop
            );
            index !== -1 &&
              (this.unfixedTableThead[index].checked = item.checked);
          });
        } else {
          // 长度相同但值不同
          this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
          const comment = JSON.stringify(this.tableThead);
          localStorage.setItem(this.tableName, comment);
          const localTableData = JSON.parse(
            localStorage.getItem(this.tableName)
          );
          this.tableTheadOptions = localTableData;
        }
      } else {
        // 长度不同
        this.tableThead = this.fixedTableThead.concat(this.unfixedTableThead);
        const comment = JSON.stringify(this.tableThead);
        localStorage.setItem(this.tableName, comment);
        const localTableData = JSON.parse(localStorage.getItem(this.tableName));
        this.tableTheadOptions = localTableData;
      }
    },
    // 渲染本地存储表格宽度
    setTableWidth() {
      const localTableData = JSON.parse(localStorage.getItem(this.tableName));
      if (localTableData) {
        for (let i = 0; i < this.tableTheadOptions.length; i++) {
          if (this.tableTheadOptions[i].label === localTableData[i].label) {
            this.tableTheadOptions[i].width = localTableData[i].width;
          }
        }
      }
    },
    // 表格宽度更改存入
    tableTitleWidth(newWidth, oldWidth, column, event) {
      for (let i = 0; i < this.unfixedTableThead.length; i++) {
        if (this.unfixedTableThead[i].label === column.label) {
          this.unfixedTableThead[i].width = newWidth;
        }
      }
      this.tableThead = this.unfixedTableThead.concat(this.fixedTableThead);
      const comment = JSON.stringify(this.tableThead);
      localStorage.setItem(this.tableName, comment);
      this.tableTheadOptions = JSON.parse(localStorage.getItem(this.tableName));
      this.tableHack = false;
      this.$nextTick(() => {
        this.tableHack = true;
      });
    },
    handleSelectionChange(data) {
      this.selectData = data;
    },
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { "background-color": "rgba(255,232,195,1) " };
      }
    },
    // 分页
    // 上一页
    handlePrev() {},
    // 下一页
    handleNext() {},
    //  显示条数更改
    handleSizeChange(val) {
      this.formDataSearch.pageNo = 1;
      this.formDataSearch.pageSize = val;
      setSessionItem("pageSize", this.tableName, val);
      this.getStoreList(this.formDataSearch);
    },
    //翻页确定
    handleChangeSize() {
      this.getStoreList(this.formDataSearch);
    },
    // 获取默认条数
    getLocalPageSize() {
      return (
        getSessionItem("pageSize", this.tableList.storeManagementList) || 10
      );
    },
    // 当前页码更改
    handleCurrentChange(val) {
      // 跳转翻页都会调这个方法
      this.formDataSearch.pageNo = val;
      this.getStoreList(this.formDataSearch);
    },
    // 分页 end
    // 高级搜索所需函数 start
    // 高级搜索展开按钮
    search(searchData) {
      let reportInOrgId = this.reportInOrgId;
      this.formDataSearch = JSON.parse(JSON.stringify(searchData));
      (this.formDataSearch.pageNo = 1),
        (this.formDataSearch.pageSize = this.getLocalPageSize());
      this.formDataSearch.reportInOrgId = reportInOrgId;
      this.getStoreList(this.formDataSearch);
    }
    // 高级搜索 end
  },
  beforeRouteLeave(to, from, next) {
    for (var key in this.$vnode.parent.parent.componentInstance.cache) {
      delete this.$vnode.parent.parent.componentInstance.cache[
        ishasAgentId(to.path, key)
      ];
    }
    next();
  }
};
</script>
<style lang="scss" scoped>
/deep/ #ccui-paging .ccui-pagination-btn {
  display: block;
}
/deep/.ccui-multifunctional-table {
  .el-table__fixed-right,
  .el-table__fixed {
    height: 100% !important;
  }
}
/deep/ .el-table__body-wrapper {
  z-index: 1;
}
</style>
